

from rest_framework import serializers
from users.models import User


import re
class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'id', # 默认只参与序列化
            'username',
            'mobile',
            'email',

            'password' # 只参与反序列化
        ]

        extra_kwargs = {
            'password': {'write_only': True},
            'username': {'min_length': 5, 'max_length': 20}
        }

    def validate(self, attrs):
        # 针对mobile自定义校验
        mobile = attrs.get('mobile')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            # 校验失败
            raise serializers.ValidationError({'mobile格式有误'})
        return attrs


    def create(self, validated_data):
        # 针对用户数据新建需要加密，模型类序列化器默认使用User.objects.create无法加密
        return User.objects.create_user(**validated_data)